<template>
    <div class="view">
        <canvas id="loveBackground"></canvas>
        <div class="content">
            <div class="submit" @click="save">下一步</div>
            <div class="face-upload">
                <cube-upload ref="upload" v-if="!device.status" v-model="files" @files-added="addedHandler" :action="uploadOption">
                    <div class="clear-fix">
                        <cube-upload-file v-for="(file, i) in files" :file="file" :key="i"></cube-upload-file>
                        <cube-upload-btn :multiple="false" v-show="files.length <= 0 ">
                            <div class="face-file" v-show="files.length <= 0 && !user.avatar">
                                <div class="default-face">
                                    <img class="default-face-img" src="@/assets/images/default-face.jpg">
                                    <div class="face-tip">上传头像</div>
                                </div>
                            </div>
                            <div class="has-img" v-if="files.length <= 0 && user.avatar!=null">
                                <img :src="user.avatar.filePath">
                                <p class="state-tip">上传头像</p>
                            </div>
                        </cube-upload-btn>
                    </div>
                    <div class="face-tip">上传头像</div>
                </cube-upload>

                <div class="app-upload-face" v-else @click="appUploadFace" :style="`background-image:url(${uploadFile.file_path})`">
                    <p class="state-tip">上传头像</p>
                </div>
            </div>
            <div class="sex-checker">
                <cube-checker v-model="sex" :options="sexOptions" type="radio" @change="">
                    <cube-checker-item v-for="item in sexOptions" :key="item.value" :option="item" :class="item.class">
                        <div class="sex-option-item">{{item.text}}</div>
                    </cube-checker-item>
                </cube-checker>
            </div>
            <div class="remark">注:为了确保社区成员的真实性，性别设置后将无法修改，请反复确认</div>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import CommonUnit from "@/unit/CommonUnit";
    import Heart from "@/unit/Heart";
    import UserEntity from "@/entity/UserEntity";
    import {updateUser} from "@/store/dispatches";


    @Component({})
    export default class MineAvatarAndSex extends Scene {
        @State("UserStore")
        public user!: InterfaceUser;
        private allElement: any[] = [];
        private sex: number = 0;
        private styleColor: number = 0;
        private uploadFile: any = {id: 0, file_path: require("@/assets/images/default-face.jpg")};
        private files: [] = [];
        private sexOptions: any[] = [{value: 1, text: "我是男生", class: "cube-checker-male"}, {value: 2, text: "我是女生", class: "cube-checker-female"}];

        @State("DeviceStore")
        private device!: any;

        @Watch("sex")
        private onChangeSex(n: number, o: number) {
            if (o === 0) {
                (<any> this).$createDialog({
                    type: "alert",
                    title: "设置性别提醒",
                    content: "为了确保社区成员的真实性，性别设置后将无法修改，请反复确认",
                }).show();
            }
        }


        private get uploadOption(): any {
            let uploadOption: any = {};
            uploadOption.target = this.api.imageUpload;
            uploadOption.fileName = "iFile";
            uploadOption.data = {type: "header"};
            uploadOption.headers = {token: this.user.token};
            uploadOption.checkSuccess = (res: any, file: any) => {
                return res.code === 1;
            };
            return uploadOption;
        }

        private addedHandler(): void {
            const file = (<any> this).files[0];
            file && (<any> this).$refs.upload.removeFile(file);
        }

        private get saveParameter(): any {
            if (this.device.status) {
                if (this.uploadFile.id > 0) {
                    let user = new UserEntity(Object.assign(this.user, {avatarId: this.uploadFile.id, gender: this.sex})).getBaseInfo;
                    return user;
                }
                let user = new UserEntity(Object.assign(this.user, {gender: this.sex})).getBaseInfo;
                return user;
            } else {
                if (this.files.length > 0) {
                    let user = new UserEntity(Object.assign(this.user, {avatarId: (<any> this).files[0].response.data.id, gender: this.sex})).getBaseInfo;
                    return user;
                }
                let user = new UserEntity(Object.assign(this.user, {gender: this.sex})).getBaseInfo;
                return user;
            }

        }

        // private get saveParameter(): any {
        //     if (this.files.length > 0) {
        //         let user = new UserEntity(Object.assign(this.user, {avatarId: (<any> this).files[0].response.data.id})).getBaseInfo;
        //         return user;
        //     }
        //     let user = new UserEntity(this.user).getBaseInfo;
        //     return user;
        // }


        private mounted() {
            this.styleColor = this.findRandom(0, 360);
            this.drawCanvas();
            this.$nextTick(() => {
                // if (!this.user.avatar) {
                //     this.showUploadNeeding();
                // }
                this.showUploadNeeding();
            });
        }

        private next(): void {
            if (this.sex == 0) {
                (<any> this).$createToast({
                    txt: "请选择性别",
                    type: "warn",
                    time: 1000
                }).show();
                return;
            }
            console.log({...this.saveParameter});
            Http.post(this.api.saveBaseInfo, {...this.saveParameter}, {token: this.user.token}).then((res) => {
                if (res.code == 1) {
                    setTimeout(() => {
                        sessionStorage.setItem("sex", String(this.sex));
                        if (this.user.type === 1) {
                            this.redirectTo({
                                name: "mineDataEdit",
                                query: {
                                    back: "mine"
                                }
                            });
                        } else {
                            this.redirectTo({
                                name: "matchmakerDataEdit",
                                query: {
                                    back: "matchmakerMine"
                                }
                            });
                        }
                        // this.navigateTo({name: "mineBaseDataInit"});
                    }, 500);
                } else {
                    this.globalSingleResultToast(res);
                }
            }).catch((res) => {
                (<any> this).$createToast({
                    time: 2500,
                    type: "error",
                    txt: "系统错误，请稍候。。。",
                    mask: true,
                }).show();
            });
        }

        private save(): void {
            if (this.sex == 0) {
                (<any> this).$createToast({
                    txt: "请选择性别",
                    type: "warn",
                    time: 1000
                }).show();
                return;
            }
            let saveToast = (<any> this).$createToast({
                time: 0,
                txt: "保存中...",
                mask: true,
            }).show();
            Http.post(this.api.saveBaseInfo, {...this.saveParameter}, {token: this.user.token}).then((res) => {
                if (res.code === 1 || this.globalSingleResultToast(res)) {
                    Http.get(this.api.getUserInfo, {}, {token: this.user.token}).then((res) => {
                        let user: any = {...res.data, ...res.data.user_info};
                        delete user.user_info;
                        updateUser(CommonUnit.objectUnderlineToHump(user));
                        saveToast = (<any> this).$createToast({
                            txt: `欢迎进入心相依婚恋平台`,
                            type: "text",
                            time: 3000,
                            onTimeout: () => {
                                if (this.user.type === 1) {
                                    this.redirectTo({
                                        name: "mineDataEdit",
                                        query: {
                                            back: "mine",
                                            isNew: !this.device.status && CommonUnit.deviceType().isAndroid ? 1 : 2
                                        }
                                    });
                                } else {
                                    this.redirectTo({
                                        name: "matchmakerDataEdit",
                                        query: {
                                            back: "matchmakerMine",
                                            isNew: !this.device.status && CommonUnit.deviceType().isAndroid ? 1 : 2
                                        }
                                    });
                                }
                            }
                        }).show();
                    });
                } else {
                    saveToast.hide();
                    this.globalSingleResultToast(res);
                }
            }).catch((res) => {
                saveToast = (<any> this).$createToast({
                    time: 2500,
                    type: "error",
                    txt: "系统错误，请稍候。。。",
                    mask: true,
                }).show();
            });
        }

        private showUploadNeeding(): void {
            (<any> this).$createDialog({
                type: "alert",
                confirmBtn: {
                    text: "我知道了",
                    active: true
                }
            }, (createElement: any) => {
                return [
                    createElement("div", {
                        "class": {
                            "face-needing-title": true
                        },
                        slot: "title"
                    }, [
                        createElement("div", {
                            "class": {
                                "face-needing-title-img": true
                            }
                        }),
                        createElement("p", "请上传本人真实头像")
                    ]),
                    createElement("p", {
                        "class": {
                            "face-needing-content": true
                        },
                        slot: "content"
                    }, "以上类型的头像，可能会无法通过审核")
                ];
            }).show();
        }

        private drawCanvas(): void {
            const canvas: any = document.getElementById("loveBackground");
            const ctx = canvas.getContext("2d");

            const w = document.body.clientWidth;
            const h = document.body.clientHeight;
            canvas.width = w;
            canvas.height = h;
            window.requestAnimationFrame(() => {
                this.drawCanvas();
            });

            const allAttribute: any = {
                num: 6,
                start_probability: 0.1,
            };


            this.styleColor += 0.1;
            ctx.fillStyle = "hsl(" + this.styleColor + ",100%,97%)";
            ctx.fillRect(0, 0, w, h);
            if (this.allElement.length < allAttribute.num && Math.random() < allAttribute.start_probability) {
                this.allElement.push(new Heart(w, h, ctx));
            }
            this.allElement.map(function(heart) {
                heart.run();
            });
        }

        private findRandom(num1: number, num2: number): number {
            return Math.random() * (num2 - num1) + num1;
        }

        private appUploadFace() {
            (<any> this).$createActionSheet({
                data: [
                    {
                        content: "从相册中选择",
                        sourceType: "PHOTOLIBRARY"
                    },
                    {
                        content: "拍摄",
                        sourceType: "CAMERA"
                    },

                ],
                onSelect: (item: any, index: any) => {
                    if (this.device.status) {
                        let toast = (<any> this).$createToast({
                            time: 0,
                            txt: item.sourceType === "CAMERA" ? "初始化相机" : "打开系统相册",
                            mask: true
                        }).show();
                        let cameraOptions = {
                            quality: 75,
                            destinationType: Camera.DestinationType.FILE_URI,
                            sourceType: item.sourceType === "CAMERA" ? Camera.PictureSourceType.CAMERA : Camera.PictureSourceType.PHOTOLIBRARY,     //照相机类型
                            allowEdit: true,
                            encodingType: Camera.EncodingType.JPEG,
                            saveToPhotoAlbum: false,
                            cameraDirection: "FRONT"
                        };
                        (<any> navigator).camera.getPicture((img: string) => {
                            Http.uploadNative(this.api.imageUpload, img, {type: "header"}, {token: this.user.token}).then((res) => {
                                if (res.code === 1) {
                                    this.uploadFile = Object.assign(this.uploadFile, res.data);
                                    toast.hide();
                                } else {
                                    toast = (<any> this).$createToast({
                                        time: 2000,
                                        txt: res.msg,
                                        mask: true,
                                        type: "error"
                                    }).show();
                                }
                            }).catch((e: any) => {
                                toast = (<any> this).$createToast({
                                    time: 2000,
                                    txt: "网络出错",
                                    mask: true,
                                    type: "error"
                                }).show();
                            });

                        }, ((error: any) => {
                            toast.hide();
                        }), cameraOptions);
                        toast.hide();
                    }

                }
            }).show();
        }
    }
</script>

<style scoped lang="stylus">
    .view
        height 100vh;
        width 100vw;
        background $theme-page-common-background-color;

        #loveBackground
            width 100vw;
            height 100vh;
            position absolute;
            top 0;
            left 0;
            opacity .9;

        .content
            padding-top var(--safe-area-inset-top);
            overflow hidden;

            .submit
                position absolute;
                line-height 35px;
                width 80px;
                top calc(var(--safe-area-inset-top) + 12px);
                right 12px;
                text-align right;
                padding-right 20px;
                color $theme-common-color;

            .face-upload
                width 92px;
                height 92px;
                margin 9vh auto 30px;
                border-radius 12px;
                border 1px solid #fff;
                overflow hidden;
                position relative;

                >>> .cube-upload
                    position relativel
                    width 90px;
                    height 90px;

                >>> .cubeic-wrong
                    display none;

                >>> .cube-upload-file-status.cubeic-right
                    display none;

                >>> .cube-upload-file_stat
                    background rgba(255, 255, 255, 0)

                >>> .cube-upload-file-def, .cube-upload-btn
                    width 90px;
                    height 90px;
                    border-radius 12px;

                >>> .cube-upload-file
                    pointer-events all;
                    position absolute;

                >>> .cube-upload-btn
                    bottom 0;
                    left 0;
                    width 90px;
                    heigh 90px;
                    z-index 2

                .face-file, .has-img
                    width 90px;
                    height 90px;
                    background #fff;
                    position relative;
                    border-radius 12px;
                    overflow hidden;

                    .default-face-img
                        display block;
                        position absolute;
                        width 90px;
                        height 90px;
                        opacity: .7;

                .has-img
                    img
                        display block;
                        position absolute;
                        width 90px;
                        height 90px;
                        opacity: .7;

            .face-tip, .state-tip
                display flex;
                justify-content center;
                align-items center;
                position absolute;
                height 24px;
                width 100%;
                bottom 0;
                left 0;
                background rgba(255, 255, 255, .5);
                font-size 12px;
                color #333;

            .sex-checker
                margin 16vh auto 10px;
                width 300px;

                >>> .cube-checker
                    display flex;
                    justify-content space-between;
                    align-items center;

                >>> .cube-checker-item
                    margin 0 !important;
                    border-radius 35px;
                    overflow hidden;
                    transition all ease-in-out .3s;

                    &::after
                        display none;

                .cube-checker-male
                    border 1px solid #69dbe7
                    color #69dbe7;

                    &.cube-checker-item_active
                        background #69dbe7;
                        color #fff;

                .cube-checker-female
                    border 1px solid #fdabb7;
                    color #fdabb7;

                    &.cube-checker-item_active
                        background #fdabb7;
                        color #fff;


                .sex-option-item
                    height 20px;
                    width 100px;
                    display flex;
                    justify-content center;
                    align-items center;
                    font-size 13px

            .remark
                position absolute;
                margin 6px 40px;
                color #FDABB7;
                line-height 1.3em;
                text-align center;

    .app-upload-face
        width 100%;
        height 100%;
        background-size cover;
        background-position center;
        position relative;
</style>
